package com.kidback.bbloc259.ui.account;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.kidback.bbloc259.api.BBNetApi;
import com.kidback.bbloc259.app.KidApplication;
import com.kidback.bbloc259.app.KidGlobal;
import com.kidback.bbloc259.app.provider.UserDataProvider;
import com.kidback.bbloc259.base.BaseActivity;
import com.kidback.bbloc259.base.lang.Delay;
import com.kidback.bbloc259.base.lang.Runnable0;
import com.kidback.bbloc259.bean.UserInfoBean;
import com.kidback.bbloc259.databinding.LoginActivityBinding;
import com.kidback.bbloc259.event.UserInfoEvent;
import com.kidback.bbloc259.network.base.ApiHelper;
import com.kidback.bbloc259.network.beans.BaseResponse;
import com.kidback.bbloc259.network.errorhandler.ResponseThrowable;
import com.kidback.bbloc259.network.observer.BaseObserver;
import com.kidback.bbloc259.ui.WebViewActivity;
import com.kidback.bbloc259.util.ActivityLaunchUtils;
import com.kidback.bbloc259.util.StatusBarUtils;
import com.kidback.bbloc259.util.StringUtils;
import com.kidback.bbloc259.util.TipUtils;
import com.kidback.bbloc259.util.ToastUtils;
import com.kidback.bbloc259.wxapi.WXService;
import com.kidback.bbloc259.wxapi.WXUserInfo;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseActivity<LoginActivityBinding> {

    //第三方app和微信通信的openApi接口
    private IWXAPI api;

    @Override
    public LoginActivityBinding getViewBinding() {
        return LoginActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {
        StatusBarUtils.setStatusBarColor(activity, 0xff715af3);

        viewBinding.titleBar.setTintColor(Color.WHITE);

        viewBinding.titleBar.setOnBackClickListener(onBackClickListener);

        viewBinding.layoutSnsWx.setOnClickListener(onClickListener);
        viewBinding.btnLogin.setOnClickListener(onClickListener);

        viewBinding.tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityLaunchUtils.launch(v.getContext(), RegisterActivity.class);
            }
        });
        viewBinding.tvLinkPrivate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.start(v.getContext(), "隐私政策", "https://www.kidback.top/BBLocationWeb/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html");
            }
        });

        viewBinding.tvLinkUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.start(v.getContext(), "用户协议", "https://www.kidback.top/BBLocationWeb/%E7%94%A8%E6%88%B7%E5%8D%8F%E8%AE%AE.html");
            }
        });

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, KidGlobal.WX_APP_ID, true);
        api.handleIntent(getIntent(), eventHandler);

        //建议动态监听微信启动广播进行注册到微信
        IntentFilter filter = new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP);
        registerReceiver(receiver, filter, RECEIVER_EXPORTED);
    }

    @Override
    protected void loadData() {

    }

    private IWXAPIEventHandler eventHandler = new IWXAPIEventHandler() {
        @Override
        public void onReq(BaseReq baseReq) {

        }

        @Override
        public void onResp(BaseResp resp) {
            //在这个方法中处理微信传回的数据
            //形参resp 有下面两个个属性比较重要
            //1.resp.errCode
            //2.resp.transaction则是在分享数据的时候手动指定的字符创,用来分辨是那次分享(参照4.中req.transaction)
            switch (resp.errCode) { //根据需要的情况进行处理
                case BaseResp.ErrCode.ERR_OK:
                    if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
                        //微信登录，正确返回，用户同意
                        String code = ((SendAuth.Resp) resp).code;
                        getAccessToken(code);
                    } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                        //微信分享
                        int type = ((SendMessageToWX.Resp) resp).getType();

                        if (StringUtils.equals(KidGlobal.SHARE_AWARD_TRANSACTION, ((SendMessageToWX.Resp) resp).transaction)) {
                            //分享领取奖励
                        }

                        finish();
                    }
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    //用户取消
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    //用户拒绝授权
                    break;
                case BaseResp.ErrCode.ERR_SENT_FAILED:
                    //发送失败
                    break;
                case BaseResp.ErrCode.ERR_UNSUPPORT:
                    //不支持错误
                    break;
                case BaseResp.ErrCode.ERR_COMM:
                    //一般错误
                    break;
                default:
                    //其他不可名状的情况
                    break;
            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 将该app注册到微信
            api.registerApp(KidGlobal.WX_APP_ID);
        }
    };

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == viewBinding.btnLogin) {
                login();
            } else if (v == viewBinding.layoutSnsWx) {
                requestWXLogin();
            }
        }
    };

    private void requestWXLogin() {
        if (!viewBinding.chkRead.isChecked()) {
            TipUtils.showMsgDuration(KidApplication.getCurrentActivity(), "请先阅读隐私协议和用户协议", Gravity.CENTER, 1000);
            return;
        }

        if (!api.isWXAppInstalled()) {
            ToastUtils.show("您还未安装微信客户端");
            return;
        }

        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }


    /**
     * 获取微信用户信息的访问令牌
     */
    private void getAccessToken(String code) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        okHttpClientBuilder.callTimeout(0, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(10_000, TimeUnit.MILLISECONDS);

        //官方请求日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String s) {
                Log.e("WXEntryActivity", s);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClientBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient okHttpClient = okHttpClientBuilder.build();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.baseUrl("https://api.weixin.qq.com/");
        retrofitBuilder.client(okHttpClient);
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create());
        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        Retrofit retrofit = retrofitBuilder.build();

        WXService wxService = retrofit.create(WXService.class);

        String appid, secret;
        appid = KidGlobal.WX_APP_ID;
        secret = KidGlobal.WX_APP_AppSecret;

        Observable<JSONObject> observable = wxService.getAccessToken(appid, secret, code, "authorization_code");
        Observer<JSONObject> observer = new Observer<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableList.add(d);
            }

            @Override
            public void onNext(JSONObject jsonObject) {
                String access_token = jsonObject.getString("access_token");
                String refresh_token = jsonObject.getString("refresh_token");
                String unionid = jsonObject.getString("unionid");
                String openid = jsonObject.getString("openid");
                String scope = jsonObject.getString("scope");
                Double expires_in_Double = jsonObject.getDouble("expires_in");
                double expires_in = expires_in_Double == null ? 0 : expires_in_Double.doubleValue();

                getWXUserInfo(access_token, openid);
            }

            @Override
            public void onError(Throwable e) {
                TipUtils.hideLoadingFixDialog();
                disposableList.add(TipUtils.showFail(activity, e.getMessage()));
            }

            @Override
            public void onComplete() {

            }
        };

        ApiHelper.request(observable, observer);

        TipUtils.showLoadingFixDialog(activity, "正在登录");
    }


    /**
     * 获取微信用户信息，如 openid、昵称、头像
     */
    private void getWXUserInfo(String access_token, String openid) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        okHttpClientBuilder.callTimeout(0, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(10_000, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(10_000, TimeUnit.MILLISECONDS);

        //官方请求日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String s) {
                Log.e("WXEntryActivity", s);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClientBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient okHttpClient = okHttpClientBuilder.build();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.baseUrl("https://api.weixin.qq.com/");
        retrofitBuilder.client(okHttpClient);
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create());
        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        Retrofit retrofit = retrofitBuilder.build();

        WXService wxService = retrofit.create(WXService.class);

        Observable<WXUserInfo> observable = wxService.getWXUserInfo(access_token, openid, "");
        Observer<WXUserInfo> observer = new Observer<WXUserInfo>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableList.add(d);
            }

            @Override
            public void onNext(WXUserInfo wxUserInfo) {

//                wxUserInfo.openid += "AA121341231";
//                wxUserInfo.nickname = "🤖🤖🤖👹🥶🤢";
//                wxUserInfo.headimgurl += "abc";

                finish();
            }

            @Override
            public void onError(Throwable e) {
                disposableList.add(TipUtils.showFail(activity, e.getMessage()));
            }

            @Override
            public void onComplete() {
                TipUtils.hideLoadingFixDialog();
            }
        };

        TipUtils.showLoadingFixDialog(activity, "网络加载中");

        ApiHelper.request(observable, observer);
    }

    private void login() {
        if (!viewBinding.chkRead.isChecked()) {
            TipUtils.showMsgDuration(KidApplication.getCurrentActivity(), "请先阅读隐私协议和用户协议", Gravity.CENTER, 1000);
            return;
        }



        String phone = viewBinding.edtPhone.getText().toString();
        String password = viewBinding.edtPwd.getText().toString();

        Observable<BaseResponse<UserInfoBean>> observable = BBNetApi.getBBService().login(phone, password);
        Observer<BaseResponse<UserInfoBean>> observer = new BaseObserver<BaseResponse<UserInfoBean>>() {

            @Override
            public void onSubscribe(Disposable d) {
                super.onSubscribe(d);
            }

            @Override
            public void onSuccess(BaseResponse<UserInfoBean> orderResponse) {
                TipUtils.hideLoadingFixDialog();

                TipUtils.showMsgFixed(KidApplication.getCurrentActivity(), "登录成功", Gravity.CENTER);

                UserDataProvider.getInst().put(orderResponse.data);
                EventBus.getDefault().post(new UserInfoEvent());

                Delay.delay(1000, new Runnable0() {
                    @Override
                    public void run() {
                        finish();
                    }
                });
            }

            @Override
            public void onFailure(ResponseThrowable e) {
                TipUtils.hideLoadingFixDialog();

                TipUtils.showMsgFixed(KidApplication.getCurrentActivity(), "登录失败\n" + e.getMessage());
            }
        };

        ApiHelper.request(observable, observer);

        TipUtils.showLoadingFixDialog(KidApplication.getCurrentActivity(), "正在登录");
    }

}
